package com.zkgengkun.console.controller;

import com.google.common.collect.Maps;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.zkgengkun.console.service.BlogService;
import com.zkgengkun.console.service.UploadService;
import com.zkgengkun.constant.SysConstants;
import com.zkgengkun.dao.mybatis.CommDAO;
import com.zkgengkun.domain.Admin;
import com.zkgengkun.domain.Blog;
import com.zkgengkun.repository.AdminRepository;
import com.zkgengkun.repository.RoleRepository;
import com.zkgengkun.support.component.AmqpSend;
import com.zkgengkun.support.component.AsyncExecutor;
import com.zkgengkun.support.component.KdApiOrderDistinguish;
import com.zkgengkun.support.json.Jacksons;
import com.zkgengkun.support.util.JedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author gengshikun
 * @date 2016/12/6
 */
@Controller
public class WebIndexController {

    private static final Logger logger = LoggerFactory.getLogger(WebIndexController.class);

    @Autowired
    private AmqpSend amqpSend;

    @Autowired
    private BlogService blogService;

    @Autowired
    private KdApiOrderDistinguish kdApiOrderDistinguish;

    @Autowired
    private UploadService uploadService;

    @Autowired
    private AsyncExecutor asyncExecutor;

    @RequestMapping(value = {"", "/index"}, method = RequestMethod.GET)
    public String index() {
        return "index";
    }

    @RequestMapping(value = "test/url")
    @ResponseBody
    public String testUrl(String url) {
        this.uploadService.uploadJpgByUrl(url);
        return "success";
    }

    @RequestMapping(value = "test/s_randmember")
    @ResponseBody
    public String testSrandmember(Integer count) {
        List<String> set = JedisUtil.getInstance().SETS.srandmember("test-s_add", count == null ? 1 : count);
        JedisUtil.getInstance().SETS.srem("test-s_add", set.toArray(new String[]{}));
        return Jacksons.json().fromObjectToJson(set);
    }

    @RequestMapping(value = "test/s_add")
    @ResponseBody
    public String testSadd(String value) {
        for (int i = 0; i < 100; i++) {
            JedisUtil.getInstance().SETS.sadd("test-s_add", i + "");
        }
        return "success";
    }

    @RequestMapping(value = "test/amqp", method = RequestMethod.GET)
    public String testKd() {
        amqpSend.sendMsg("Hello Springboot!");
        Map<String, Object> map = Maps.newHashMap();
        map.put("hello", "Hello Map!");
        amqpSend.sendMap(SysConstants.AMQP_ROUTINGKEY_MAP, map);
        return "index";
    }

    @RequestMapping(value = "test/kd", method = RequestMethod.GET)
    public String testAmqp() {
        try {
            String result = kdApiOrderDistinguish.getOrderTracesByJson("308552291983");

//            Map map = Jacksons.json().fromJsonToMap(result);
//            List list = (List) map.get("Shippers");
//            Map ship = (Map) list.get(0);

            System.out.println(result);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "index";
    }


    @RequestMapping(value = "test/exception_json", method = RequestMethod.GET)
    public String json() throws Exception {
        throw new NullPointerException();
    }

    @RequestMapping(value = "test/json", method = RequestMethod.GET)
    public ModelAndView testJson() throws Exception {
        ModelAndView model = new ModelAndView();
        // 转Json
        MappingJackson2JsonView jsonView = new MappingJackson2JsonView();
        model.setView(jsonView);
        model.addObject("status", Boolean.FALSE);
        model.addObject("msg", "失败");
        return model;
    }

    @RequestMapping(value = "test/redis", method = RequestMethod.GET)
    @ResponseBody
    public String testRedis() {

        JedisUtil.getInstance().STRINGS.setEx("boot-test", 100, "redis-test");

        String test = JedisUtil.getInstance().STRINGS.get("boot-test");
        System.out.println(test);

        return "success";
    }

    @RequestMapping(value = "test/redis_service")
    @ResponseBody
    public Map testRedisService(Model model) {
        Map<String, Object> result = Maps.newHashMap();
        result.put("blog1", this.blogService.getOne("402881a65aa6cfa1015aa6d3cb350000").getBlogId());
        return result;
    }

    @RequestMapping(value = "test/redis_test")
    @ResponseBody
    public String testRedisTest() {
        Blog blog = this.blogService.getOneByTitle("testRedis");
        return blog.getTitle();
    }

    @RequestMapping(value = "test")
    public String test() {
        return "test";
    }

    @RequestMapping(value = "test/thread")
    public String testThread() {
        logger.info("test-thread start");
        for (int i = 1; i <= 50; i++) {
            this.asyncExecutor.test1(i);
        }

        return "index";
    }

    @RequestMapping(value = "test/delaymq")
    public String testDelayMQ() {
        Map<String, String> test = Maps.newHashMap();
        test.put("123", "aaa");
        amqpSend.sendDelayMap(test, -5);

        return "index";
    }

    @RequestMapping(value = "520", method = RequestMethod.GET)
    public String ILU() {
        return "520";
    }

    @RequestMapping(value = "520", method = RequestMethod.POST)
    public String ILUPOST() {
        return "520";
    }

    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private AdminRepository adminRepository;

    @RequestMapping(value = "test/toTable")
    public String testToTable(){
        Admin admin = new Admin();
        admin.setUsername("test3");
        admin.setPassword("test3");
        admin.setRoleList(Arrays.asList(this.roleRepository.findOne("1")));

//        this.adminRepository.save(admin);

//        List<Admin> list = this.adminRepository.getByRoleList(Arrays.asList("1"));
        List<Admin> list = this.adminRepository.findByRoleList(Arrays.asList(this.roleRepository.findOne("1")));
        System.out.println(list);

        return "index";
    }

    @Autowired
    private CommDAO commDAO;

    @RequestMapping(value = "test/mybatis")
    public String testMybatis(){

//        Admin admin = this.adminRepository.getOne("402881a65d07a186015d07a2003b0001");
//        System.out.println(admin);

        return "index";
    }


    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.1.38");
        factory.setUsername("root");
        factory.setPassword("qweASDzxc");
        factory.setPort(5672);
        Connection connection = factory.newConnection();
        connection.close();
    }

}
